package com.credit.jumu.calculator.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.credit.jumu.calculator.BuildConfig;
import com.credit.jumu.calculator.R;
import com.credit.jumu.calculator.base.BaseActivity;
import com.credit.jumu.calculator.calculatorapp.CalculatorApp_;
import com.credit.jumu.calculator.utils.DataSharedPreference;
import com.credit.jumu.calculator.utils.JsonUtils;
import com.credit.jumu.calculator.utils.LogUtils;
import com.credit.jumu.calculator.utils.MD5Encoder;
import com.credit.jumu.calculator.utils.SignUtil;
import com.credit.jumu.calculator.utils.SystemUtil;
import com.credit.jumu.calculator.utils.ToastUtil;
import com.credit.jumu.calculator.utils.TypeUtils;
import com.credit.jumu.calculator.utils.UrlUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import net.sf.json.JSONObject;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;

import java.util.LinkedHashMap;

/**
 * Created by Administrator on 2017/11/29/029.
 */
@EActivity(R.layout.fragment_find)
public class SignActivity extends BaseActivity implements View.OnClickListener {
	private int time = 60;
	private int timerWhat = 1001;
	public int layoutType = 1;//0登录,1注册,2,忘记密码
	//登录的处理
	@ViewById
	RelativeLayout signinlauout, registerlayout;//总,注册
	@ViewById
	ImageView close1, backregister, closeregister;//登录关闭,注册返回,注册关闭
	@ViewById
	EditText signnum1, passnum1;//手机号,密码
	@ViewById
	TextView forgot, tosign1, toregister1, tosign2,agreement;//,忘记密码去登录,注册确认注册用户协议
	@ViewById
	TextView barheight;
	//注册的处理
	@ViewById
	EditText signnum, et_sendcode, passnum;//手机号,验证码,密码
	@ViewById
	TextView getcode;//获取验证码
	@ViewById
	LinearLayout toregister;//注册协议
	private DataSharedPreference ds;

	//忘记密码的处理
	@ViewById
	TextView appicon;//获取验证码

	@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
	@AfterViews
	public void initView() {
		RelativeLayout.LayoutParams Params1 = (RelativeLayout.LayoutParams) barheight.getLayoutParams();
		Params1.height = getNavigationBarHeight();
		barheight.setLayoutParams(Params1);
		toAllWindow();

		if (null == ds) {
			ds = new DataSharedPreference(this);
		}
		ds.setUUID(SystemUtil.getAndroidId(getApplicationContext()));
		close1.setOnClickListener(this);
		forgot.setOnClickListener(this);
		tosign1.setOnClickListener(this);
		toregister1.setOnClickListener(this);
		getcode.setOnClickListener(this);
		tosign2.setOnClickListener(this);
		closeregister.setOnClickListener(this);
		backregister.setOnClickListener(this);
		agreement.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.agreement:
				//registerXieyiUrl
				String agreementUrl = ds.getRegisterXieyiUrl();
				if(TextUtils.isEmpty(agreementUrl)){
					return;
				}
				Intent intent = new Intent(SignActivity.this, MyWebActivity.class);
				intent.putExtra("url", agreementUrl);
				startActivity(intent);
				break;
			case R.id.close1:
				SignActivity.this.finish();
				break;
			case R.id.forgot://去忘记密码
				signinlauout.setVisibility(View.GONE);
				registerlayout.setVisibility(View.VISIBLE);
				appicon.setText("忘记密码");
				toregister.setVisibility(View.INVISIBLE);
				tosign2.setText("重置密码");
				layoutType = 2;
				break;
			case R.id.tosign1://去登录
				if (TextUtils.isEmpty(signnum1.getText().toString())) {
					ToastUtil.showShortToast("请先输入手机号码");
				} else if (TextUtils.isEmpty(passnum1.getText().toString())) {
					ToastUtil.showShortToast("请先输入密码");
				} else {
					goSign(signnum1.getText().toString(), passnum1.getText().toString());
				}

				break;
			case R.id.toregister1:
				signinlauout.setVisibility(View.GONE);
				registerlayout.setVisibility(View.VISIBLE);
				appicon.setText("注册");
				toregister.setVisibility(View.VISIBLE);
				tosign2.setText("注册");
				layoutType = 1;
				break;
			case R.id.getcode:
				String num = signnum.getText().toString();
				if (TextUtils.isEmpty(num)) {
					ToastUtil.showShortToast("请先输入手机号码");
					return;
				}
				getCode(num);
				break;
			case R.id.tosign2://去注册
				if (layoutType == 1) {//是注册
					if (TextUtils.isEmpty(signnum.getText().toString())) {
						ToastUtil.showShortToast("请输入手机号码");
					} else if (TextUtils.isEmpty(et_sendcode.getText().toString())) {
						ToastUtil.showShortToast("请输入验证码");
					} else if (TextUtils.isEmpty(passnum.getText().toString())) {
						ToastUtil.showShortToast("请输入密码");
						break;
					} else {
						gotoRegister(signnum.getText().toString(), passnum.getText().toString(),
								et_sendcode.getText().toString());
					}
				} else if (layoutType == 2) {//是忘记密码

					if (TextUtils.isEmpty(signnum.getText().toString())) {
						ToastUtil.showShortToast("号码不能为空");
					} else if (TextUtils.isEmpty(et_sendcode.getText().toString())) {
						ToastUtil.showShortToast("验证码不能为空");
					} else if (TextUtils.isEmpty(passnum.getText().toString())) {
						ToastUtil.showShortToast("密码不能为空");
					} else {
						toReset(signnum.getText().toString(), et_sendcode.getText().toString(), passnum.getText().toString());
					}
				}
				break;

			case R.id.backregister:
				layoutType = 0;
				signinlauout.setVisibility(View.VISIBLE);
				registerlayout.setVisibility(View.GONE);
				break;
			case R.id.closeregister:
				this.finish();
				break;
		}
	}

	//登录
	public void goSign(String num, String pass) {
		LinkedHashMap<String, String> mapSign = new LinkedHashMap<>();
		mapSign.put("deviceCode", ds.getUUID());
		mapSign.put("intefaceType", CalculatorApp_.intefaceType);
		mapSign.put("mobile", num);
		mapSign.put("passWord", MD5Encoder.encodeBase64(pass));
		mapSign.put("source", CalculatorApp_.source);
		mapSign.put("terminalId", "A");
		mapSign.put("timeStamp", SystemUtil.getSystemTime());
		mapSign.put("version", BuildConfig.VERSION_NAME);
		mapSign.put("key", CalculatorApp_.key);

		LinkedHashMap<String, String> mapPramas = new LinkedHashMap<>();
		mapPramas.put("accountId", "");
		mapPramas.put("deviceCode", ds.getUUID());
		mapPramas.put("intefaceType", CalculatorApp_.intefaceType);
		mapPramas.put("mobile", num);
		mapPramas.put("passWord", MD5Encoder.encodeBase64(pass));
		mapPramas.put("sign", MD5Encoder.encode(SignUtil.getSign(mapSign)));
		mapPramas.put("source", CalculatorApp_.source);
		mapPramas.put("terminalId", "A");
		mapPramas.put("timeStamp", SystemUtil.getSystemTime());
		mapPramas.put("token", "");
		mapPramas.put("version", BuildConfig.VERSION_NAME);

		OkGo.<String>post(UrlUtil.LOGINSURFIX)
				.params(mapPramas)
				.execute(
						new StringCallback() {
							@Override
							public void onSuccess(Response<String> response) {
								if (!TextUtils.isEmpty(response.body())) {
									JSONObject responseJson = JsonUtils.getJsonObject(response.body().toString());
									String code = TypeUtils.getJsonString(responseJson, "code", "");
									String message = TypeUtils.getJsonString(responseJson, "message", "");
									ToastUtil.showShortToast(message);
									if (!TextUtils.isEmpty(code) && "9999".equals(code)) {


										ToastUtil.showShortToast("登录成功");
										if (null != ds) {
											ds.setAccountId(TypeUtils.getJsonString(responseJson, "accountId", ""));
											ds.setToken(TypeUtils.getJsonString(responseJson, "token", ""));
											ds.setIsLog(true);
											ds.setAccount(TypeUtils.getJsonString(responseJson, "userMobile", ""));
											initUserInfo();
										}
										SignActivity.this.finish();
									}
								}
								LogUtils.println("zhangyiyionSuccessSign------" + response.body());
							}

							@Override
							public void onError(Response<String> response) {
								ToastUtil.showShortToast("登录失败");
								LogUtils.println("zhangyiyionErrSign------" + response.body() + response.message() + response.code());
							}
						}
				);
	}

	private void initUserInfo() {
		//获取详细信息
		LinkedHashMap<String, String> mapSign = new LinkedHashMap<>();
		if(ds.getIsLog()){
			mapSign.put("accountId", ds.getAccountId());
			mapSign.put("deviceCode", ds.getUUID());
			mapSign.put("intefaceType",  CalculatorApp_.intefaceType);
			mapSign.put("source", CalculatorApp_.source);
			mapSign.put("terminalId", "A");
			mapSign.put("timeStamp", SystemUtil.getSystemTime());
			mapSign.put("token", ds.getToken());
			mapSign.put("version", BuildConfig.VERSION_NAME);
			mapSign.put("key", CalculatorApp_.key);
		}else {
			mapSign.put("deviceCode", ds.getUUID());
			mapSign.put("intefaceType",  CalculatorApp_.intefaceType);
			mapSign.put("source", CalculatorApp_.source);
			mapSign.put("terminalId", "A");
			mapSign.put("timeStamp", SystemUtil.getSystemTime());
			mapSign.put("version", SystemUtil.getVersionCode(this));
			mapSign.put("key", "e83fgehkJuHeXinYongContosedce9ff");
		}

		LinkedHashMap<String, String> mapPramas = new LinkedHashMap<>();
		mapPramas.put("accountId", ds.getAccountId());
		mapPramas.put("deviceCode", ds.getUUID());
		mapPramas.put("intefaceType", CalculatorApp_.intefaceType);
		mapPramas.put("sign", MD5Encoder.encode(SignUtil.getSign(mapSign)));
		mapPramas.put("source", CalculatorApp_.source);
		mapPramas.put("terminalId", "A");
		mapPramas.put("timeStamp", SystemUtil.getSystemTime());
		mapPramas.put("token", ds.getToken());
		mapPramas.put("version", BuildConfig.VERSION_NAME);

		OkGo.<String>post(UrlUtil.USERINFOSURFIX)//设置信息
				.tag(this)
				.params(mapPramas)
				.execute(
						new StringCallback() {
							@Override
							public void onSuccess(Response<String> response) {
								LogUtils.println("zhangyiyioninitUserInfo------1111111" + response.body());
								if (!TextUtils.isEmpty(response.body())) {
									JSONObject responseJson = JsonUtils.getJsonObject(response.body().toString());
									JSONObject data = TypeUtils.getJsonObject(responseJson, "userInfo");
									if (null == ds) return;
									ds.setAboutUrl(TypeUtils.getJsonString(data, "aboutUrl", ""));
									ds.setRegisterXieyiUrl(TypeUtils.getJsonString(data, "registerXieyiUrl", ""));
									ds.setRedirectUrl(TypeUtils.getJsonString(data, "redirectUrl", ""));
								}
							}

							@Override
							public void onError(Response<String> response) {
								LogUtils.println("zhangyiyionerroinitUserInfo------1111111" + response.body());
							}
						}
				);
	}


	//重置密码
	public void toReset(String phone, String code, String pwd) {
		LinkedHashMap<String, String> mapSign = new LinkedHashMap<>();
		mapSign.put("actionType", "forgetpwd");
		mapSign.put("deviceCode", ds.getUUID());
		mapSign.put("intefaceType", CalculatorApp_.intefaceType);
		mapSign.put("mobile", phone);
		mapSign.put("passWord", MD5Encoder.encodeBase64(pwd));
		mapSign.put("smsCode", code);
		mapSign.put("source", CalculatorApp_.source);
		mapSign.put("terminalId", "A");
		mapSign.put("timeStamp", SystemUtil.getSystemTime());
		mapSign.put("version", BuildConfig.VERSION_NAME);
		mapSign.put("key", CalculatorApp_.key);

		LinkedHashMap<String, String> mapPramas = new LinkedHashMap<>();
		mapPramas.put("accountId", "");
		mapPramas.put("actionType", "forgetpwd");
		mapPramas.put("deviceCode", ds.getUUID());
		mapPramas.put("intefaceType", CalculatorApp_.intefaceType);
		mapPramas.put("mobile", phone);
		mapPramas.put("passWord", MD5Encoder.encodeBase64(pwd));
		mapPramas.put("sign", MD5Encoder.encode(SignUtil.getSign(mapSign)));
		mapPramas.put("smsCode", code);
		mapPramas.put("source", CalculatorApp_.source);
		mapPramas.put("terminalId", "A");
		mapPramas.put("timeStamp", SystemUtil.getSystemTime());
		mapPramas.put("token", "");
		mapPramas.put("version", BuildConfig.VERSION_NAME);

		OkGo.<String>post(UrlUtil.FINDPASSWORDSURFIX)
				.params(mapPramas)
				.execute(
						new StringCallback() {
							@Override
							public void onSuccess(Response<String> response) {
								if (!TextUtils.isEmpty(response.body())) {
									LogUtils.println("zhangyiyi------LoginPassSet" + response.body());
									JSONObject responseJson = JsonUtils.getJsonObject(response.body().toString());
									String code = TypeUtils.getJsonString(responseJson, "code", "");
									String message = TypeUtils.getJsonString(responseJson, "message", "");
									ToastUtil.showShortToast(message);
									if ("9999".equals(code)) {
										ToastUtil.showShortToast("密码重置完成,请登录");
										layoutType = 0;
										signinlauout.setVisibility(View.VISIBLE);
										registerlayout.setVisibility(View.GONE);
									}
								}
							}

							@Override
							public void onError(Response<String> response) {
								LogUtils.println("zhangyiyiLoginPassSeterr------" + response.body() + response.message() + response.code());
							}
						}
				);

	}

	//去注册
	public void gotoRegister(String num, String pass, String code) {
		LinkedHashMap<String, String> mapSign = new LinkedHashMap<>();
		mapSign.put("actionType", "register");
		mapSign.put("deviceCode", ds.getUUID());
		mapSign.put("intefaceType", CalculatorApp_.intefaceType);
		mapSign.put("mobile", num);
		mapSign.put("passWord", MD5Encoder.encodeBase64(pass));
		mapSign.put("smsCode", code);
		mapSign.put("source", CalculatorApp_.source);
		mapSign.put("terminalId", "A");
		mapSign.put("timeStamp", SystemUtil.getSystemTime());
		mapSign.put("version", BuildConfig.VERSION_NAME);
		mapSign.put("key", CalculatorApp_.key);

		LinkedHashMap<String, String> mapPramas = new LinkedHashMap<>();
		mapPramas.put("accountId", "");
		mapPramas.put("actionType", "register");
		mapPramas.put("deviceCode", ds.getUUID());
		mapPramas.put("intefaceType", CalculatorApp_.intefaceType);
		mapPramas.put("mobile", num);
		mapPramas.put("passWord", MD5Encoder.encodeBase64(pass));
		mapPramas.put("sign", MD5Encoder.encode(SignUtil.getSign(mapSign)));
		mapPramas.put("smsCode", code);
		mapPramas.put("source", CalculatorApp_.source);
		mapPramas.put("terminalId", "A");
		mapPramas.put("timeStamp", SystemUtil.getSystemTime());
		mapPramas.put("token", "");
		mapPramas.put("version", BuildConfig.VERSION_NAME);

		OkGo.<String>post(UrlUtil.REGISTERSURFIX)
				.params(mapPramas)
				.execute(
						new StringCallback() {
							@Override
							public void onSuccess(Response<String> response) {


								JSONObject responseJson = JsonUtils.getJsonObject(response.body().toString());
								String code = TypeUtils.getJsonString(responseJson, "code", "");
								String message = TypeUtils.getJsonString(responseJson, "message", "");
								if ("1016".equals(code)) {
									ToastUtil.showShortToast("注册完成,请登录");
									layoutType = 0;
									signinlauout.setVisibility(View.VISIBLE);
									registerlayout.setVisibility(View.GONE);
								} else {
									ToastUtil.showShortToast(message);
								}

								LogUtils.println("zhangyiyionSuccessRegister------" + response.body());
							}

							@Override
							public void onError(Response<String> response) {
								LogUtils.println("zhangyiyionErrRegister------" + response.body() + response.message() + response.code());
							}
						}
				);


	}

	//获取注册验证码
	public void getCode(String num) {
		LinkedHashMap<String, String> mapSign = new LinkedHashMap<>();
		mapSign.put("deviceCode", ds.getUUID());
		mapSign.put("intefaceType", CalculatorApp_.intefaceType);
		mapSign.put("mobile", num);
		mapSign.put("source", CalculatorApp_.source);
		mapSign.put("terminalId", "A");
		mapSign.put("timeStamp", SystemUtil.getSystemTime());
		mapSign.put("version", BuildConfig.VERSION_NAME);
		mapSign.put("key", CalculatorApp_.key);

		LinkedHashMap<String, String> mapPramas = new LinkedHashMap<>();
		mapPramas.put("accountId", "");
		mapPramas.put("deviceCode", ds.getUUID());
		mapPramas.put("intefaceType", CalculatorApp_.intefaceType);
		mapPramas.put("mobile", num);
		mapPramas.put("sign", MD5Encoder.encode(SignUtil.getSign(mapSign)));
		mapPramas.put("source", CalculatorApp_.source);
		mapPramas.put("terminalId", "A");
		mapPramas.put("timeStamp", SystemUtil.getSystemTime());
		mapPramas.put("token", "");
		mapPramas.put("version", BuildConfig.VERSION_NAME);
		OkGo.<String>post(UrlUtil.SENDCODESURFIX)
				.params(mapPramas)
				.execute(
						new StringCallback() {
							@Override
							public void onSuccess(Response<String> response) {
								if (!TextUtils.isEmpty(response.body())) {
									JSONObject responseJson = JsonUtils.getJsonObject(response.body().toString());
									String code = TypeUtils.getJsonString(responseJson, "code", "");
									String message = TypeUtils.getJsonString(responseJson, "message", "");
									if ("9999".equals(code)) {
										changePhoneCodeState(getcode);
									}
									ToastUtil.showShortToast(message);
								}
							}

							@Override
							public void onError(Response<String> response) {
								LogUtils.println("zhangyiyionGetMessageCodeerr------" + response.body() + response.message() + response.code());
							}
						}
				);
	}

	public void changePhoneCodeState(TextView code) {
		if (null == code) return;
		this.getcode = code;
		getcode.setBackgroundResource(R.drawable.bg_sure);
		getcode.setEnabled(false);

		getcode.setText("验证码(60s)");
		time = 60;
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub

				try {
					while ((time >= 0)) {
						time--;
						Thread.sleep(1000);
						Message msg = Message.obtain();
						msg.what = timerWhat;
						msg.arg1 = time;
						mHandler.sendMessage(msg);
					}

				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					LogUtils.outException(e);
				}
			}
		}).start();
	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == timerWhat) {
				if (msg.arg1 > 0) {
					getcode.setText("验证码(" + msg.arg1 + "s)");
				} else {
					getcode.setText("验证码");
					getcode.setBackgroundResource(R.drawable.bg_appthem);
					getcode.setEnabled(true);
				}
			}

		}
	};
}
